﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TVGuide.Enums;
using TVGuide.DataAccess.Common;
using TVGuide.DataAccess.Repository;
using TVGuide.Common;

namespace TvGuide.UI.Models
{
    public class ProgramData
    {
        public int ZoneHour = Utils.ZoneHour;
        private CommonStr comm_str;
        private int lang;
        private List<ProgCategory> CatList;

        public List<ProgCategory> Catlist
        {
            get { return this.CatList; }
        }
        public ProgramData(int lng)
        {
            this.lang = lng;
            this.comm_str = new CommonStr(ResUtil.GetLang(lng));
            this.MianTitle = this.comm_str.MAINTITLE_LBL;
            CategoryInit(lng);
        }

        private void CategoryInit(int lng)
        {
            this.CatList = new List<ProgCategory>();
            var cat = CategoryRepository.Instance().Get(o=>o.Priority!=null).OrderBy(o=>o.Priority);
            foreach (var category in cat)
                this.CatList.Add(new ProgCategory() { color = "#"+category.Color, CatId = category.Id, CatName = category.Name, CatDispName = setCatdispName(category.Id) });
        }

        

        private string setCatdispName(short id)
        {
            string name = "";
            switch (id)
            {
                case 1:
                    name = this.comm_str.NEWS_LBL;
                    break;
                case 2:
                    name = this.comm_str.FILMS_LBL;
                    break;
                case 3:
                    name = this.comm_str.MUSIC_LBL;
                    break;
                case 4:
                    name = this.comm_str.CHILDREN_LBL;
                    break;
                case 5:
                    name = this.comm_str.SPORT_LBL;
                    break;
                case 8:
                    name = this.comm_str.HUMOR_LBL;
                    break;
                
            }

            return name;
            
        }
       
        public void ProgramsList(DateTime date, int ch,int? lineindex)
        {
            string datestr = date.Day.ToString() + "." + date.Month.ToString() + "." + date.Year.ToString();
            int shareid = (int)((date - DateTime.Now.AddHours(Utils.ZoneHour)).TotalDays) + 1;
            List<ProgsShowList> CurrShowList = new List<ProgsShowList>();
            var DataAcc = ProgramRepository.Instance();
            string ChName = ChannelRepository.Instance().Get(ch).DisplayName;
            string chImageURL = ChannelRepository.Instance().Get(ch).ImageURL;
            DateTime CompareDate = new DateTime(date.Year, date.Month, date.Day, 8, 0, 0);
            var CurrList = DataAcc.Get(o => o.ChannelId == ch && o.Date >= CompareDate && o.Date < CompareDate.AddHours(24)).ToList();
            int? differInd = null;
            int index = 0;
            
            foreach (var cl in CurrList)
            {
                if (date.DayOfYear == DateTime.Now.AddHours(Utils.ZoneHour).DayOfYear && index < CurrList.Count && DateTime.Now.AddHours(Utils.ZoneHour) >= cl.Date && DateTime.Now.AddHours(Utils.ZoneHour) < CurrList[index + 1].Date)
                    differInd = index;
                if (index < (CurrList.Count - 1) && date.DayOfYear == DateTime.Now.AddHours(Utils.ZoneHour).DayOfYear && index < CurrList.Count && DateTime.Now.AddHours(Utils.ZoneHour).AddDays(1) >= cl.Date && DateTime.Now.AddHours(Utils.ZoneHour).AddDays(1) < CurrList[index + 1].Date)
                    differInd = index;

                index++;
                CurrShowList.Add(new ProgsShowList() {CatID=cl.CategoryId ,Name = cl.Name, Time = string.Format("{0:d2}", cl.Date.Hour) + ":" + string.Format("{0:d2}", cl.Date.Minute) });

            }
            
            
            System.Text.StringBuilder StrHtml = new System.Text.StringBuilder();
            // this.ProgsList = CurrShowList;
            if (CurrShowList.Count == 0)
                return;

            StrHtml.Append(string.Format("<table id='listing_table' class='Home-page_Prog_listing' CELLSPACING=0><tr><td class='Home-page_Prog_Div_Programs_Title' colspan='4'><span class='Home-page_Prog_Div_Programs_Progname_Span'>{0}</span><span class='Home-page_Prog_Div_Programs_Date'>{1}</span></td></tr>", ChName, date.ToShortDateString()));
            

            for (int i = 0; i < index; i++)
            {
                string aaa = HttpUtility.HtmlEncode(CurrShowList[i].Name);
                string time = CurrShowList[i].Time;
                string HTMLencodedName = HttpUtility.HtmlEncode(CurrShowList[i].Name);
                string HTMLdecodedName = HttpUtility.HtmlDecode(CurrShowList[i].Name);
                string chName = ChName;
                string CatId = CurrShowList[i].CatID==null?"":"Category_"+CurrShowList[i].CatID.ToString();

                string twitlink = HttpUtility.HtmlEncode("http://twitter.com/intent/tweet?text=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "/http://www.tvcuyc.am/" + "&redirect_uri=http://tvcuyc.am/close.html"); // link=http://tvcuyc.am/Home/Home/" + ch + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + chImageURL + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" at " + time + " on " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                string link = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945& link=http://tvcuyc.am/Home/Home/" + ch + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + chImageURL + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                if (differInd != null)
                {
                    if (i == differInd)
                    {
                        StrHtml.Append("<tr class='Home-page_Prog_onAir " + CatId + "'><td><input type='hidden' class='progcathiden' value ='"+CatId+"'/> " + time + " </td><td> " + HTMLdecodedName + " </td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");
                        continue;
                    }
                }

                if (lineindex != null && lineindex == i)
                {
                    StrHtml.Append("<tr class='Home-page_Prog_onShare " + CatId + "'><td><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + time + " </td><td> " + HTMLdecodedName + " </td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");
                    continue;
                }

                if (i % 2 == 0)
                    StrHtml.Append("<tr class='Home-page_Prog_listing_darker " + CatId + "'><td class='Home-page_Prog_listing_time'><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + time + " </td><td class='Home-page_Prog_listing_name'> " + HTMLdecodedName + " </td><td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' href ='" + link + "' onclick=\"return popitup('" + link + "')\" ><img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");

                else
                    StrHtml.Append("<tr class='Home-page_Prog_listing_lighter " + CatId + "'><td class='Home-page_Prog_listing_time'> <input type='hidden' class='progcathiden' value ='" + CatId + "'/>" + time + "</td><td class='Home-page_Prog_listing_name'> " + HTMLdecodedName + " </td><td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /></a></td></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");
            }
            StrHtml.Append("</table>");

            this.ProgsListHtml = StrHtml.ToString();

        }

        public void ChannelsList()
        {
            List<ChannelShowList> CurrChShowList = new List<ChannelShowList>();
            var DataAcc = ChannelRepository.Instance();
            foreach (var ch in DataAcc.GetAllItems())
            {
                if (ch.Enabled > 0)
                    CurrChShowList.Add(new ChannelShowList() { Name = ch.Name, DispName=ch.DisplayName, ID = ch.Id, ImgUrl = ch.ImageURL });
            }

            this.ChList = CurrChShowList;
        }

        public void NowRuning(DateTime date)
        {
          //  if (date.Hour >= 0 && date.Hour <= 5)
          //      date = date.AddHours(-5);
            SetOnAirVal(date);
            string datestr = date.Day.ToString() + "." + date.Month.ToString() + "." + date.Year.ToString();
            int shareid = (int)((date - DateTime.Now.AddHours(Utils.ZoneHour)).TotalDays) + 1;
            DateTime dategr =  date.AddHours(4.5);
            DateTime dateles = date.AddHours(-4.5);

            var NowRunnList = (from Progs in ProgramRepository.Instance().Get(o => (o.Date < dategr && o.Date > dateles) )
                               from Chan in ChannelRepository.Instance().GetAllItems()
                               where Progs.ChannelId == Chan.Id
                               orderby Chan.Enabled
                               select new {Progs.CategoryId, Progs.Date, PrName = Progs.Name, ChName = Chan.Name, ChdispName = Chan.DisplayName, chID = Progs.ChannelId, ChimgUrl = Chan.ImageURL }).ToList();
            if (NowRunnList.Count() == 0)
            {
                this.ProgsListHtml = "";
                return;
            }
            if (NowRunnList.Count == 0)
            {
                this.ProgsListHtml = "";
                return;
            }
            string chname;
            string nextchname;
            List<int> validlist = new List<int>();
            DateTime stdate;
            DateTime enddate;

            for (int i = 0; i < NowRunnList.Count; i++)
            {
                chname = NowRunnList[i].ChName;
                stdate = NowRunnList[i].Date;
                if(i < NowRunnList.Count - 2)
                {
                    enddate = NowRunnList[i+1].Date;
                    nextchname = NowRunnList[i+1].ChName;
                }
                else
                {
                    enddate = NowRunnList[i].Date;
                    nextchname = NowRunnList[i].ChName;
                }
                if (stdate <= date && enddate >= date && chname == nextchname)
                {
                    validlist.Add(i);
                    for(int j = i+1;j < NowRunnList.Count; j++)
                        if(j<NowRunnList.Count-2 && NowRunnList[j].ChName!=NowRunnList[j+1].ChName)
                        {
                            i = j;
                            break;
                        }
                }
            }

               


            System.Text.StringBuilder StrHtml = new System.Text.StringBuilder();



            StrHtml.Append(string.Format("<table id='listing_table' class='Home-page_Prog_listing' CELLSPACING=0><tr><td class='Home-page_Prog_Div_Programs_Title' colspan='5'>{0}<span class='Home-page_Prog_Div_Programs_Date'>{1}</span></td></tr>", "", date.ToShortDateString()));


            for (int i = 0; i < validlist.Count; i++)
            {
                string aaa = HttpUtility.HtmlEncode(NowRunnList[i].PrName);
                string time = string.Format("{0:d2}", NowRunnList[validlist[i]].Date.Hour) + ":" + string.Format("{0:d2}", NowRunnList[validlist[i]].Date.Minute);
                string HTMLencodedName = HttpUtility.HtmlEncode(NowRunnList[validlist[i]].PrName);
                string HTMLdecodedName = HttpUtility.HtmlDecode(NowRunnList[validlist[i]].PrName);
                string chName = NowRunnList[validlist[i]].ChdispName;
                string churl = NowRunnList[validlist[i]].ChimgUrl;
                string CatId = NowRunnList[validlist[i]].CategoryId == null ? "" : "Category_" + NowRunnList[validlist[i]].CategoryId.ToString();

                string twitlink = HttpUtility.HtmlEncode("http://twitter.com/intent/tweet?text=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "/http://www.tvcuyc.am/" + "&redirect_uri=http://tvcuyc.am/close.html"); // link=http://tvcuyc.am/Home/Home/" + ch + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + chImageURL + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" at " + time + " on " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                string link = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945& link=http://tvcuyc.am/Home/Home/" + NowRunnList[validlist[i]].chID + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + NowRunnList[validlist[i]].ChimgUrl + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                //  <td class=''><img src='" + churl + "'alt ='" + chName + "'> </td>
                if (i % 2 == 0)
                    StrHtml.Append("<tr class='Home-page_Prog_listing_darker " + CatId + " '><td class='Home-page_Prog_listing_Chanal'><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + chName + " </td><td class='Home-page_Prog_listing_time_Now'> " + time + " </td><td class='Home-page_Prog_listing_name_Now'> " + HTMLdecodedName + " </td>  <td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' href ='" + link + "' onclick=\"return popitup('" + link + "')\" ><img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");

                else
                    StrHtml.Append("<tr class='Home-page_Prog_listing_lighter " + CatId + " '><td class='Home-page_Prog_listing_Chanal'><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + chName + " </td><td class='Home-page_Prog_listing_time_Now'>" + time + "</td><td class='Home-page_Prog_listing_name_Now'> " + HTMLdecodedName + " </td>   <td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='share' border='0' /></a></td></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='share' border='0' /> </a></td></tr>");
            }
            StrHtml.Append("</table>");


            this.ProgsListHtml = StrHtml.ToString();

        }

        private void SetOnAirVal(DateTime date)
        {
            this.OnAirVal = string.Format("{0:d2}", date.Hour) + ":" + string.Format("{0:d2}", date.Minute);
        }

        public static DateTime SetOnAirDate(int? val)
        {
            DateTime tocount = DateTime.Now.AddHours(Utils.ZoneHour);
            DateTime stdate = new DateTime(tocount.Year, tocount.Month, tocount.Day, 8, 0, 0);
            if (val == null)
                return DateTime.Now.AddHours(Utils.ZoneHour);
            return stdate.AddHours(((int)val) / 2).AddMinutes(((int)val % 2) * 30);
        }

        public static DateTime GetPrDate(ref int? id)
        {
            DateTime date = DateTime.Now.AddHours(Utils.ZoneHour);
            date = DateTime.Now.AddHours(Utils.ZoneHour).AddDays((int)id - 1);
         //   if (date.Hour >= 0 && date.Hour <=5)
          //      date = date.AddHours(-5);
            return date;
        }

        public static int ParseParam(ref int? combineId)
        {
            int lineindex = (int)combineId % 100;
            combineId = combineId/100;
            return lineindex;
        }

        public void MakeingWeekDays()
        {
            int currIndex = (int)DateTime.Now.AddHours(Utils.ZoneHour).DayOfWeek;
            if (currIndex == 0)
                currIndex = 7;
            weekDays[0] = this.comm_str.YESTERDAY_LBL;
            weekDays[1] = this.comm_str.TODAY_LBL;
            weekDays[2] = this.comm_str.TOMORROW_LBL;

            weekDays[3] = GetWeekDayName(currIndex, 2);
            weekDays[4] = GetWeekDayName(currIndex, 3);
            weekDays[5] = GetWeekDayName(currIndex, 4);
            weekDays[6] = GetWeekDayName(currIndex, 5);
            weekDays[7] = GetWeekDayName(currIndex, 6);
            Onair = this.comm_str.NOWPENDING_LBL;
        }

        private string GetWeekDayName(int dayInd, int ind)
        {
            switch (dayInd)
            {
                case 1:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 3:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 4:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 5:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 6:
                            return this.comm_str.SUNDAY_LBL;
                            
                    }
                    break;
                case 2:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 3:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 4:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 5:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 6:
                            return this.comm_str.MONDAY_LBL;
                            
                    }
                    break;
                case 3:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 3:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 4:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 5:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 6:
                            return this.comm_str.TUESDAY_LBL;
                            
                    }
                    break;
                case 4:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 3:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 4:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 5:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 6:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                    }
                    break;
                case 5:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 3:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 4:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 5:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 6:
                            return this.comm_str.THURSDAY_LBL;
                            
                    }
                    break;
                case 6:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 3:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 4:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 5:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 6:
                            return this.comm_str.FRIDAY_LBL;
                            
                    }
                    break;
                case 7:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 3:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 4:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 5:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 6:
                            return this.comm_str.SATURDAY_LBL;
                            
                    }
                    break;
            }
            return "";
        }

       

        // public List<ProgsShowList> ProgsList { get; set; }
        public string ProgsListHtml { get; set; }
        public List<ChannelShowList> ChList { get; set; }
        public int ChID { get; set; }
        public int Lng
        {
            get
            {
                return this.lang;
            }
        }

        public string OnAir
        {
            get
            {
                return this.Onair;
            }
        }
        public string MianTitle {get;set;}
        public string OnAirVal {get;set;}
       
        public int WeekDayID { get; set; }
        // public static List<string> weekDaysConst = new List<string>() { "Monday", "Thusday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
        public List<string> weekDays = new List<string>() { "","", "", "", "", "", "", "" };
        public List<string> WeekDay { get { return this.weekDays; } }
        public string Onair;

    }

    public class ProgsShowList
    {
        public string Time { get; set; }
        public string Name { get; set; }
        public short? CatID { get; set; }

    }

    public class ChannelShowList
    {

        public int ID { get; set; }
        public string Name { get; set; }
        public string ImgUrl { get; set; }
        public string DispName { get; set; }
    }

    public class ProgCategory
    {
        public string CatName { get; set; }
        public short CatId { get; set; }
        public string CatDispName { get; set; }
        public string color { get; set; }
    }

}